package xyz.twj.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import xyz.twj.gateway.service.FeignDemo;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : TianWenjian
 */
@Component
public class LoginFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);

    @Autowired
    FeignDemo feignDemo;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        log.debug("call micro service:" + feignDemo.hello());

        RequestContext context = RequestContext.getCurrentContext();
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        log.debug("send {} request to {}", request.getMethod(), request.getRequestURL().toString());

        //获取传来的参数accessToken
        Object accessToken = request.getParameter("accessToken");
        if (accessToken == null) {
            log.warn("access token is empty");
            //过滤该请求，不往下级服务去转发请求，到此结束
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("未登录或者权限校验失败");
            ctx.getResponse().setContentType(MediaType.TEXT_HTML_VALUE);
            return null;
        }
        //如果有token，则进行路由转发
        log.debug("access token ok");

        return null;
    }
}
